package com.zzzyh.captcha.controller;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    public static final String CAPTCHA_KEY = "HOME_KAPTCHA_SESSION_KEY";
    public static final String CAPTCHA_DATE = "HOME_KAPTCHA_SESSION_DATE";
    public static final Long CAPTCHA_OUT_DATE = 60* 1000L;

    @RequestMapping("/checkCaptcha")
    public boolean checkCaptcha(String captcha,HttpSession session) {
        String key =(String)session.getAttribute(CAPTCHA_KEY);
        System.out.println(key);
        System.out.println(captcha);
        if(!StringUtils.hasLength(captcha) || !StringUtils.hasLength(key))
            return false;
        Date date = (Date) session.getAttribute(CAPTCHA_DATE);
        if(date == null || new Date().getTime()-date.getTime() > CAPTCHA_OUT_DATE )
            return false;
        return key.equalsIgnoreCase(captcha);
    }
}
